import { Component, ElementRef, Input, OnInit, Output, EventEmitter, ViewChild } from '@angular/core';

@Component({
  selector: 'app-diyprogress',
  templateUrl: './diyprogress.component.html',
  styleUrls: ['./diyprogress.component.css']
})
export class DiyprogressComponent implements OnInit {

  touch: any = {};
  currPercent: number = 1;

  @ViewChild('progress') progress: ElementRef;
  @ViewChild('progressBar') progressBar: ElementRef;
  @ViewChild('progressBtn') progressBtn: ElementRef;

  @Input() maxMin: any[] = []; //一维数据 ，0，最大值，1，最小值
  //当前百分比
  @Input() set setPercent(value: number) {
    console.log("setPercent");
    this.currPercent = value;
    let that = this;
    setTimeout(() => {
      that.initProgress();
    }, 500);

  }

  @Output() updatePercent = new EventEmitter<any>(); //更新百分比


  constructor() { }

  ngOnInit(): void {
  }

  progressTouchStart(e) {
    console.log("TouchStart", e.pageY);
    //创建一个标志，意思它已经初始化完
    this.touch.initiated = true;
    console.log(this.touch.top)
    //记录滚动条的位置
    if (this.touch.top > 0) {
      this.touch.startY = this.touch.top + e.pageY;
    } else {
      this.touch.startY = e.pageY;
    }

  }
  progressTouchMove(e) {
    //如果初始化完则什么都不做
    if (!this.touch.initiated) {
      return;
    }
    console.log(e.pageY);
    const deltaY = this.touch.startY - e.pageY; //计算差值 向上是负值
    //max 的0  意思不能小于0 、、、、min，不能超过整个滚动条的宽度
    console.log(this.progressBar);
    const offsetWidth = Math.min(
      // this.$refs.progressBar.clientHeight,
      this.progressBar.nativeElement.clientHeight,
      Math.max(0, deltaY)
    );
    //保存当前滚动条的位置
    this.touch.top = offsetWidth;
    console.log("TouchMove", this.touch.top);
    this._offset(offsetWidth);
  }

  progressMouseUp(e) {
    this.touch.initiated = false;
  }

  progressMouseleave() {
    this.touch.initiated = false;
  }

  //初始化进度条
  initProgress() {
    let dValue = this.maxMin[0] - this.maxMin[1];
    let actualDValue = this.currPercent - this.maxMin[1];
    let offsetWidth = this.progressBar.nativeElement.clientHeight * (actualDValue / dValue);
    console.log(this.progressBar);
    if (actualDValue <= 0) {
      this.currPercent = this.maxMin[1];
      offsetWidth = 0;
    }

    if (actualDValue >= dValue) {
      this.currPercent = this.maxMin[0];
      offsetWidth = this.progressBar.nativeElement.clientHeight;
    }

    console.log(offsetWidth);
    this.touch.top = offsetWidth;
    this._offset(offsetWidth);
    this.updatePercent.emit(this.currPercent);
  }

  //偏移方法
  _offset(offsetWidth) {
    this.progress.nativeElement.style.height = `${offsetWidth}px`; //获取进度条的位置，距离左右的距离
    this.progressBtn.nativeElement.style.transform = `translate3d(0,${-offsetWidth}px,0)`; //小球的偏移
  }
}
